package saucaca.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import saucaca.Adapter.RingtoneAdapter;
import saucaca.Adapter.TopicAdapter2;
import saucaca.CustomView.ProgressBarCircularIndeterminate;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.RingtoneObject;
import saucaca.Object.TopicObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;

public class TopicFragment2 extends Fragment implements OnScrollListener {
	private MainActivity mActivity = null;
	String page = "0";
	String pageSize = "";
	int xpage = 0;
	private ListView listView;
	boolean loadingMore;
	private View mView_EmptyLoading = null;
	private ProgressBar progressBar;
	ImageView imgEmpty, imgError;
//	private SwipeRefreshLayout mSwipeLayout;
	ArrayList<TopicObject> listTopics;
	TextView txtStatus;

	TopicAdapter2 adapter;
	ProgressBarCircularIndeterminate progressBarFooter;
	int m_PreviousTotalCount = 0;

	@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.listview2, container, false);
		findviewByID(view);
		new GetFromServices().execute("");

		mActivity.myActionBar.setMenu(R.string.menu_chude, false, true);
		return view;
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden)
			mActivity.myActionBar.setMenu(R.string.menu_chude, false, true);
	}

	private void findviewByID(View view) {
		listView = (ListView) view.findViewById(R.id.layoutlistview_listview);
		mView_EmptyLoading = view.findViewById(R.id.empty_loading);
		listView.setEmptyView(mView_EmptyLoading);
		progressBar = (ProgressBar) mView_EmptyLoading.findViewById(R.id.empty_loading_progress);
		imgEmpty = (ImageView) mView_EmptyLoading.findViewById(R.id.empty_loading_NoItem);
		imgError = (ImageView) mView_EmptyLoading.findViewById(R.id.empty_loading_Error);
		txtStatus = (TextView) mView_EmptyLoading.findViewById(R.id.empty_loading_text);
		listView.setOnScrollListener(this);
		progressBarFooter = (ProgressBarCircularIndeterminate) view.findViewById(R.id.progressBarloadmore);
		listTopics = new ArrayList<TopicObject>();
		adapter = new TopicAdapter2(mActivity, listTopics);
		listView.setAdapter(adapter);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof MainActivity) {
			mActivity = (MainActivity) activity;
		}
	}

	class GetFromServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... param) {
			if (m_PreviousTotalCount > 0)
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						progressBarFooter.setVisibility(View.VISIBLE);
					}
				});
			page = Integer.toString(xpage);
			String str = WServiceLib.TopicList(page, pageSize, "2");
			// BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null) {
				try {
					if(getActivity()!=null)
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							progressBarFooter.setVisibility(View.GONE);
						}
					});
					List<TopicObject> listNews = JsonReader.topicList(result);
					for (int i = 0; i < listNews.size(); i++) {
						boolean isAdded = false;
						for (int j = 0; j < listTopics.size(); j++) {
							if (listTopics.get(j).getCATE_CODE().equals(listNews.get(i).getCATE_CODE())) {
								isAdded = true;
							}
						}
						if (!isAdded) {
							listTopics.add(listNews.get(i));
							adapter.update(listTopics);
						}
					}
					loadingMore = false;
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (totalItemCount == 0 || adapter == null)
			return;
		if (m_PreviousTotalCount == totalItemCount) {
			return;
		}
		boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount - 3;
		if (loadMore && firstVisibleItem > 0 && totalItemCount - m_PreviousTotalCount >= 10) {
			m_PreviousTotalCount = totalItemCount;
			xpage += 1;
			new GetFromServices().execute("");
		}

	}
}
